package com.coincalf.wallet.blockchain.client;

import com.coincalf.feign.CoinServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.http.HttpService;

import javax.annotation.PostConstruct;

@Component
public class Web3jSingleton {

    @Autowired
    private CoinServiceClient coinServiceClient;

    private static CoinServiceClient coinClient;

    @PostConstruct
    public void init() {
        Web3jSingleton.coinClient = coinServiceClient;
    }

    private Web3jSingleton() {
    }

    //    private static volatile Geth geth = null;
    private static volatile Web3j web3j = null;
    private static volatile Admin admin = null;

    public static Web3j getWeb3j() {
        if (web3j == null) {
            synchronized (Web3jSingleton.class) {
                if (web3j == null) {
                    String ethUrl = coinClient.selectRpcServerUrl("ETH");
                    web3j = Web3j.build(new HttpService(ethUrl));
                }
            }
        }
        return web3j;
    }

    public static Admin getAdmin() {
        if (admin == null) {
            synchronized (Web3jSingleton.class) {
                if (admin == null) {
                    admin = Admin.build(new HttpService(coinClient.selectRpcServerUrl("ETH")));
                }
            }
        }
        return admin;
    }

//    public static Geth getGeth() {
//        if (geth == null) {
//            synchronized (Web3jSingleton.class) {
//                if (geth == null) {
//                    geth = Geth.build(new HttpService(PropertiesUtil.getProperty("block.chain.eth.url", "http://127.0.0.1:8545/")));
//                }
//            }
//        }
//        return geth;
//    }

}
